// 发送请求
$('.btn').click(function () {
    const title = $('.title input').val()
    const category_id = $('.category select').val()
    const content = $('.content textarea').val()
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));

    if (!title) {
        myAlert(false, '标题不能为空')
        return false
    }

    if (!category_id) {
        myAlert(false, '分类不能为空')
        return false
    }

    if (!content) {
        myAlert(false, '内容不能为空')
        return false
    }

    addArticleRequest({
        title,
        category_id,
        content,
        user_id: userInfo.id
    })
})

// 请求
function addArticleRequest(data) {
    $.ajax({
        url: 'http://localhost:8081/api/articleAdd.php',
        type: 'post',
        data: data
    }).then(res => {
        if (res.code === 1) {
            myAlert(true, '发布成功')
            $('.form')[0].reset()
        } else {
            myAlert(false, res.msg)
        }
    })
}

// 获取分类
async function getCategoryRequest() {
    const res = await $.ajax({
        url: 'http://localhost:8081/api/getCategory.php',
        type: 'get'
    })
    return res
}

// 创建分类 Fragment
function createCategoryFragment(categoryData) {
    const fragment = document.createDocumentFragment()
    categoryData.data.forEach(item => {
        const option = document.createElement('option')
        option.value = item.id
        option.innerHTML = item.name
        fragment.append(option)
    })
    return fragment
}

// 设置分类
async function setCategory() {
    const selectArticle = document.querySelector('.category .select')
    const selectHeader = document.querySelector('.header .search .select')
    const categoryData = await getCategoryRequest()
    if (categoryData.code === 1) {
        selectArticle.appendChild(createCategoryFragment(categoryData))
        selectHeader.appendChild(createCategoryFragment(categoryData))
    }
}
setCategory()